'use client';

import { Popover, PopoverButton, PopoverPanel } from '@headlessui/react';
import { LogoutOutlined, SettingOutlined } from '@ant-design/icons';
import { useAtomValue } from 'jotai';
import React, { startTransition, useMemo } from 'react';
import Link from 'next/link';
import { userAtom } from 'src/model';
import Image from 'next/image';
import clsx from 'clsx';
import { logout } from 'src/actions/user';
import { usePathname, useRouter } from 'next/navigation';

export interface ProfileProps {
  className?: string;
  avatarClassName?: string;
  /**
   * 是否全宽，全宽时，头像和名称会在同一行展示
   * @default false
   */
  block?: boolean;
}

function ProfileNoMemoized(props: ProfileProps) {
  const { className, avatarClassName, block } = props;

  const user = useAtomValue(userAtom);
  const router = useRouter();
  const pathname = usePathname();

  const loginUrl = useMemo(() => {
    const searchParams = new URLSearchParams();
    searchParams.set('redirect', pathname);
    return `/login?${searchParams.toString()}`;
  }, [pathname]);

  if (user?.id) {
    // User is logged in
    return (
      <Popover className={clsx(block && 'w-full')}>
        <PopoverButton
          className={clsx(
            'focus:outline-none cursor-pointer hover:opacity-80 transition-opacity',
            block && 'w-full flex items-center gap-2',
            avatarClassName
          )}
        >
          <div className="avatar" title={user.name}>
            <div className="w-10 rounded-full ring ring-base-100">
              {user.avatar ? (
                <Image src={user.avatar} alt={user.name} width={40} height={40} priority />
              ) : (
                <Image
                  src="/images/default_avatar.svg"
                  alt={user.name}
                  width={40}
                  height={40}
                  priority
                  className="invert dark:invert-0"
                />
              )}
            </div>
          </div>
          {block && <span className="text-sm font-bold font-sans truncate">{user.name}</span>}
        </PopoverButton>
        <PopoverPanel
          transition
          anchor="bottom"
          className={clsx(
            'flex flex-col w-36 border shadow-lg rounded-box text-sm/6 backdrop-blur-xl transition duration-200 ease-in-out z-[999]',
            'bg-base-100 border-gray-200 dark:border-neutral-700',
            '[--anchor-gap:--spacing(1)] data-closed:-translate-y-2 data-closed:opacity-0'
          )}
        >
          <div
            className="inline-block px-5 pt-4 truncate text-left font-bold font-sans"
            title={user.name}
          >
            {user.name}
          </div>
          <ul className="menu w-full">
            <li>
              <Link href="/profile">
                <SettingOutlined />
                账号设置
              </Link>
            </li>
            <li>
              <button
                type="button"
                onClick={() => {
                  startTransition(async () => {
                    await logout();
                    router.push(pathname);
                  });
                }}
              >
                <LogoutOutlined />
                退出登录
              </button>
            </li>
          </ul>
        </PopoverPanel>
      </Popover>
    );
  }
  // User is not logged in
  return (
    <Link href={loginUrl} className={clsx(block && 'w-full')}>
      <button
        className={clsx(
          'btn rounded-full border-none truncate',
          'bg-gradient-to-r from-purple-700 to-purple-500 dark:from-purple-900 dark:to-purple-700 text-white hover:bg-gradient-to-l',
          block && 'w-full',
          className
        )}
      >
        登录
      </button>
    </Link>
  );
}

export const Profile = React.memo(ProfileNoMemoized);
